package cn.idongjia.task.center.init;

import cn.idongjia.task.center.TaskCenter;
import cn.idongjia.task.center.config.TaskCenterConfig;
import cn.idongjia.task.common.command.CommandUtil;
import cn.idongjia.task.common.siginal.ShutDownHandler;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.log4j.Logger;
import sun.misc.Signal;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by renxianlong on 16/3/30.
 */
public class TaskCenterStarter {

    public static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");

    public static Logger logger = Logger.getLogger(TaskCenterStarter.class);

    public static String ROOT_PATH = System.getProperty("task.home");

    public static String CONF_FILE = ROOT_PATH + "/conf/task-center.properties";

    public static void main(String[] args) {
        long beginTm = new Date().getTime();
        System.out.print(format.format(beginTm) + ":系统开始启动");
        logger.info(format.format(beginTm) + ":系统开始启动");
        //解析命令
        CommandLine commandLine =
                CommandUtil.parseCmdLine("taskcenter", args, buildCommandlineOptions(new Options()),
                        new PosixParser());

        TaskCenterConfig config = new TaskCenterConfig();

        if(new File(CONF_FILE).exists()){
            CommandUtil.propertiesFileToObject(CONF_FILE, config);
        }

        if (commandLine.hasOption("c")) {
            String configFile = commandLine.getOptionValue("c");
            if (null == configFile) {
                existByError("找不到配置文件,系统异常终止");
            }
            CommandUtil.propertiesFileToObject(configFile, config);
        }

        if (commandLine.hasOption("p")) {
            CommandUtil.printObjectProperties(null, config);
            return;
        }

        TaskCenter taskCenter = new TaskCenter(config);
        taskCenter.start();

        ShutDownHandler shutDownHandler = new ShutDownHandler(taskCenter);
        Signal.handle(new Signal("TERM"), shutDownHandler);

        long endTm = new Date().getTime();
        long elapse = endTm - beginTm;
        logger.info(format.format(endTm) + ":系统启动成功,耗时:" + elapse);
        System.out.print(format.format(endTm) + ":系统启动成功,耗时:" + elapse);

    }


    public static Options buildCommandlineOptions(final Options options) {
        Option opt = new Option("c", "configFile", true, "taskcenter config properties file");
        opt.setRequired(false);
        options.addOption(opt);

        opt = new Option("p", "printConfigItem", false, "Print all config item");
        opt.setRequired(false);
        options.addOption(opt);

        return options;
    }

    public static void existByError(String errorMsg) {
        System.out.print(errorMsg);
        System.exit(-1);
    }
}
